import { getToken } from '@/utils/auth'
import { requestGet, requestPost } from '@/api/system/common'
/**
 * 移动端模版解析
 * @type {{}}
 */
export function mobile(option = {}) {
  return {
    props: {
      temp: {
        type: Object,
        default() {
          return {}
        }
      },
      showHeader: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        defaultImage: require('@/assets/images/avatar.png'),
        userImage: require('@/assets/images/user.png'),
        baseURL: process.env.VUE_APP_BASE_API.substring(
          0,
          process.env.VUE_APP_BASE_API.length - 1
        ),
        query: {
          blurry: ''
        }, // 一般用于办事大厅模糊查询
        loading: false,
        column: {}, // 栏目配置信息
        columns: [], // tabs 组件使用
        dataList: [],
        cid: null,
        isRefresh: false, // 是否定时刷新
        refreshTime: 30, // 刷新时间（秒）
        setting: null,
        active: 0, // tabs 默认选中项
        activeId: null, // tabs选中项ID
        template: null, // tabs 嵌入的模版
        isMore: false, // tabs 是否打开更多
        queryList: [], // 一般用于办事大厅模版 查询条件
        activeNames: [], // 办事大厅查询条件选中项
        call: {}, // 移动端统计组件，点击打开统计模块详情组件使用
        entity: {} // 用户个人中心模版
      }
    },
    computed: {
      // 块状区域样式
      borderStyle() {
        // 是否全屏展示
        if (this.temp.sfdzqp === true) {
          return {
            position: 'absolute',
            left: '0px',
            right: '0px',
            top: '0px',
            bottom: '0px',
            paddingTop: this.temp.mtop + 'px',
            paddingLeft: this.temp.mleft + 'px',
            paddingRight: this.temp.mright + 'px',
            paddingBottom: this.temp.mbotton + 'px'
          }
        }
        return {
          minHeight: this.temp.defaultHeight,
          paddingTop: this.temp.mtop + 'px',
          paddingLeft: this.temp.mleft + 'px',
          paddingRight: this.temp.mright + 'px',
          paddingBottom: this.temp.mbotton + 'px'
        }
      },
      // 内容区域样式
      bodyStyle() {
        let boxShadow = '' // 是否显示边框
        const borderRadius = this.temp.topLeft + 'px ' +
          this.temp.topRight + 'px ' + this.temp.bottomRight + 'px ' + this.temp.bottomLeft + 'px' // 圆角大小
        if (this.temp.sfxsbk) { // 如果显示边框
          boxShadow = '0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)'
        }
        let backgroundColor = '' // 背景颜色
        if (this.temp.sfxsbjs) {
          backgroundColor = this.temp.backgroundColor
        }
        return {
          boxShadow: boxShadow,
          borderRadius: borderRadius,
          backgroundColor: backgroundColor,
          color: this.temp.fontColor,
          minHeight: this.temp.defaultHeight
        }
      },
      // 用于计算服务列表
      liStyle() {
        let width = 100
        if (option.tabs === 'statistics') {
          width = (100 / this.column.size).toFixed(2)
        } else {
          width = (100 / this.column.row).toFixed(2)
        }
        return { width: width + '%' }
      }
    },
    watch: {
      temp: {
        handler(newData) {
          if (this.showHeader) {
            this.column = JSON.parse(newData.data.pzx)
            this.cid = newData.data.id
          } else {
            this.column = JSON.parse(newData.pzx)
            this.cid = newData.id
          }
          this.setting = this.column
          this.columns = this.column.data
          if (undefined !== this.columns && this.columns !== null && this.columns.length > 0) {
            this.activeId = this.columns[this.active].temp
          }
          if (this.setting.isRefresh !== undefined && this.setting.isRefresh === true) {
            this.isRefresh = this.setting.isRefresh
          }
          if (this.setting.refreshTime !== undefined && this.setting.refreshTime !== null) {
            this.refreshTime = this.setting.refreshTime
          }
          if (undefined !== this.column.query && this.column.query !== null) {
            this.queryList = this.column.query
          } else {
            this.queryList = []
          }
          if (option.tabs === 'tabs') { // tabs 组件
            this.initEntity()
          } else if (option.tabs === 'service') { // 服务组件
            this.initService()
          } else if (option.tabs === 'statistics') { // 统计组件
            if (this.showHeader) {
              this.dataList = this.column.data
            } else {
              this.dataList = this.column.dataList
            }
          } else if (option.tabs === 'user') { // 用户组件
            this.initUserData()
          } else {
            this.initData()
          }
        },
        immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
        deep: false // formType为对象时，设置为true，此属性监听对象发生变化
      }
    },
    methods: {
      // 普通模版数据解析
      initData() {
        this.loading = true
        if (getToken()) {
          requestGet('rest/api/temp/v2/column/analysis/tmp', { cid: this.cid })
            .then((res) => {
              const { data } = res
              if (undefined !== data.data && data.data !== null) {
                console.log(data)
                this.dataList = data.data
                if (this.isRefresh === true) {
                  this.timer = setTimeout(this.initData, this.refreshTime * 1000)
                }
              }
              this.loading = false
            })
            .catch(() => {
              this.loading = false
              this.dataList = []
            })
        } else {
          requestGet('rest/api/guest/temp/v2/column/analysis/tmp', { cid: this.cid })
            .then(res => {
              const { data } = res
              if (undefined !== data.data && data.data !== null) {
                this.dataList = data.data
                if (this.isRefresh === true) {
                  this.timer = setTimeout(this.initData, this.refreshTime * 1000)
                }
              }
              this.loading = false
            })
            .catch(() => {
              this.dataList = []
              this.loading = false
            })
        }
      },
      // 打开详情页方法解析
      openEntity(data) {
        // 打开详情页
        if (this.column.isOpenEntity) {
          // 允许打开详情页
          const params = []
          let url = ''
          if (
            undefined !== this.column.entityParams &&
            this.column.entityParams !== null &&
            this.column.entityParams.length > 0
          ) {
            this.column.entityParams.forEach(item => {
              const obj = { code: item.code, value: data[item.value] }
              params.push(obj)
            })
          }
          if (this.column.entityOpenType === 1) {
            // 地址参数的方式打开
            url = data[this.column.entityUrl]
          }
          if (this.column.entityOpenType === 2) {
            // 地址传参查询
            if (
              undefined !== this.column.params &&
              this.column.params !== null &&
              this.column.params.length > 0
            ) {
              url = this.column.entityUrl
              this.column.params.forEach(item => {
                url = url.replace(
                  new RegExp(
                    '\\$\\{([\\s]*?)(' + item.code + '{1})([\\s]*?)([^}])*\\}'
                  ),
                  data[item.column]
                )
              })
            }
          }
          const object = {
            title: data[this.column['title']],
            params: params,
            setting: this.temp,
            entityTemp: this.column.entityTemplateId,
            temp: this.column.entityTemp,
            openType: this.column.entityOpenType,
            url: url
          }
          this.$emit('fetch-entity', object)
        }
      },
      // 普通模版回掉函数
      callBack() {
        if (this.temp.dkfs === 2) {
          // 自定义打开方式
          if (undefined !== this.temp.path && this.temp.path !== null) {
            window.open(this.temp.path, '_blank')
          }
        } else if (this.temp.dkfs === 1) {
          this.$emit('fetch-data', this.temp)
        } else {
          console.log('')
        }
      },
      // tabs 模版 点击切换按钮出发事件
      headerClick(item, index) {
        this.active = index
        this.activeId = item.temp
        this.initEntity()
      },
      // tabs 模版解析
      initEntity() {
        if (this.activeId !== null) {
          if (getToken()) {
            requestGet('rest/api/temp/v1/column/manager/one', { id: this.activeId })
              .then(res => {
                const { data } = res
                const path = data.mbdl + '/' + data.mbfl + '/' + data.mb
                this.template = () => import(`@/template/${path}`)
                this.column = data
                this.isMore = this.columns[this.active].isMore
                this.column.dkfs = this.columns[this.active].dkfs
                this.column.path = this.columns[this.active].path
                this.column.showHeader = true
                this.column.menuId = this.temp.menu.id
                this.column.menuName = this.temp.menu.name
                this.column.columnName = this.columns[this.active].label
              })
          } else {
            requestGet('rest/api/guest/temp/v2/column/analysis/one', { id: this.activeId })
              .then(res => {
                const { data } = res
                const path = data.mbdl + '/' + data.mbfl + '/' + data.mb
                this.template = () => import(`@/template/${path}`)
                this.column = data
                this.isMore = this.columns[this.active].isMore
                this.column.dkfs = this.columns[this.active].dkfs
                this.column.path = this.columns[this.active].path
                this.column.showHeader = true
                this.column.menuId = this.temp.menu.id
                this.column.menuName = this.temp.menu.name
                this.column.columnName = this.columns[this.active].label
              })
          }
        }
      },
      // tabs模版切换使用
      callBackEntity(data) {
        data.column = this.column
        this.$emit('fetch-entity', data)
      },
      // tabs模版打开更多回掉
      callTabsBack() {
        if (this.column.dkfs === 2) {
          // 自定义打开方式
          if (undefined !== this.column.path && this.column.path !== null) {
            window.open(this.column.path, '_blank')
          }
        } else if (this.column.dkfs === 1) {
          this.$emit('fetch-data', this.column)
        } else {
          console.log('')
        }
      },
      // 服务收藏
      scfw(data) {
        // 收藏服务
        this.loading = true
        requestPost('rest/api/service/entity/collection', { serviceId: data.id }).then(res => {
          if (res.state === 200) {
            this.$notify({
              title: '收藏成功',
              message: '服务收藏成功！',
              type: 'success'
            })
            this.loading = false
          } else {
            this.$notify({
              title: '收藏失败！',
              message: res.msg,
              type: 'warning'
            })
            this.loading = false
          }
        })
      },
      // 服务取消收藏
      qxsc(data) {
        // 取消收藏
        this.loading = true
        requestPost('rest/api/service/entity/collection/del', { serviceId: data.id }).then(res => {
          if (res.state === 200) {
            this.obj.sfsc = false
            this.$notify({
              title: '取消成功',
              message: '服务取消收藏成功！',
              type: 'success'
            })
            this.loading = false
          } else {
            this.$notify({
              title: '取消失败！',
              message: res.msg,
              type: 'warning'
            })
            this.loading = false
          }
        })
      },
      initService() {
        this.activeNames = []
        if (getToken()) {
          requestGet('rest/api/service/v1/all/analysis/default/auth/all', this.query)
            .then(res => {
              const { data } = res
              this.dataList = data.data
              this.dataList.forEach((item, index) => {
                this.activeNames.push(index)
              })
            })
            .catch(() => {
              this.dataList = []
            })
        } else {
          requestGet('rest/api/config/v1/service/list/defalult/all', this.query)
            .then(res => {
              const { data } = res
              this.dataList = data.data
              this.dataList.forEach((item, index) => {
                this.activeNames.push(index)
              })
            })
            .catch(() => {
              this.dataList = []
            })
        }
      },
      // 办事大厅选择项查询功能
      queryClick(obj) {
        this.query[obj.code] = obj.value
        this.initService()
      },
      queryObject() {
        this.initService()
      },
      // 统计组件使用
      initStatisticsEntity(id, label) {
        if (id !== null) {
          requestGet('rest/api/temp/v1/column/manager/one', { id: id })
            .then((res) => {
              const { data } = res
              this.call = data
              this.call.menuId = this.temp.menu.id
              this.call.menuName = this.temp.menu.name
              this.call.showHeader = true
              this.call.columnName = label
              this.$emit('fetch-data', this.call)
            })
        }
      },
      // 统计组件使用
      callStatisticsBack(item) {
        if (item.isOpenMore === true) {
          if (item.openType === 1) { // 模版的方式打开
            this.initStatisticsEntity(item.temp, item.label)
          }
          if (item.openType === 2 && undefined !== item.openUrl && item.openUrl !== null) {
            window.open(item.openUrl, '_blank')
          }
        }
      },
      initUserData() {
        requestGet('rest/api/temp/v2/column/analysis/tmp', { cid: this.cid }).then(res => {
          const { data } = res
          if (undefined !== data.data && data.data !== null) {
            this.dataList = data.data
            if (this.dataList.length > 0) {
              this.entity = this.dataList[0]
            }
          }
        }).catch(() => {
          this.dataList = []
        })
      },
      // 用户模版中使用
      userCallBack(data) {
        if (undefined !== data) {
          data.showHeader = true
          data.menuId = this.temp.menu.id
          data.menuName = this.temp.menu.name
          this.$emit('fetch-data', data)
        }
      }
    }
  }
}

/**
 * 移动端模版更多页面
 */
export function more(option = {}) {
  return {
    props: {
      temp: {
        type: Object,
        default: () => {
          return {}
        }
      }
    },
    data() {
      return {
        dataList: [], // 数据列表
        setting: {}, // 配置项
        column: {}, // 配置项，同上
        loading: false, // 价值状态
        moreLoading: false, // 更多加载状态
        defaultImage: require('@/assets/images/avatar.png'),
        pagerSize: 0,
        form: {
          page: 1,
          size: 15,
          cid: null
        }
      }
    },
    computed: {
      // 计算是否加载状态
      isLoading() {
        const pagers =
          Math.ceil((this.pagerSize + this.form.size) / this.form.size) - 1
        if (this.form.page < pagers) {
          return true
        } else {
          return false
        }
      }
    },
    watch: {
      temp: {
        handler(newName, oldName) {
          // 值发生变化时
          if (undefined !== newName && newName !== null) {
            this.setting = JSON.parse(newName.pzx)
            console.log(this.setting)
            this.column = this.setting
            this.form.cid = newName.id
            this.initData(newName.id)
          }
        },
        immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
        deep: false // formType为对象时，设置为true，此属性监听对象发生变化
      }
    },
    methods: {
      loadingMore() {
        const pagers =
          Math.ceil((this.pagerSize + this.form.size) / this.form.size) - 1
        if (this.form.page < pagers) {
          this.form.page = this.form.page + 1
          this.initData()
        }
      },
      initData() {
        this.moreLoading = true
        if (getToken()) {
          requestGet('rest/api/temp/v2/column/analysis/sys', this.form)
            .then(res => {
              const { data } = res
              if (undefined !== data.data && data.data !== null) {
                this.dataList = this.dataList.concat(data.data)
                console.log('数据1:', this.dataList)
                this.pagerSize = data.pager.totalElements
              }
              this.moreLoading = false
            })
            .catch(() => {
              this.moreLoading = false
              this.dataList = []
            })
        } else {
          requestGet('rest/api/guest/temp/v2/column/analysis/sys', this.form)
            .then(res => {
              const { data } = res
              if (undefined !== data.dataList && data.dataList !== null) {
                this.dataList = data.dataList
                this.pagerSize = data.pager.totalElements
              }
              this.moreLoading = false
            })
            .catch(() => {
              this.moreLoading = false
              this.dataList = []
            })
        }
      },
      queryObject() {
        this.form.page = 1
        this.dataList = []
        this.initData()
      },
      openEntity(data) {
        // 打开详情页
        if (this.column.isOpenEntity) {
          // 允许打开详情页
          const params = []
          let url = ''
          if (
            undefined !== this.column.entityParams &&
            this.column.entityParams !== null &&
            this.column.entityParams.length > 0
          ) {
            this.column.entityParams.forEach(item => {
              const obj = { code: item.code, value: data[item.value] }
              params.push(obj)
            })
          }
          if (this.column.entityOpenType === 1) {
            // 地址参数的方式打开
            url = data[this.column.entityUrl]
          }
          if (this.column.entityOpenType === 2) {
            // 地址传参查询
            if (
              undefined !== this.column.params &&
              this.column.params !== null &&
              this.column.params.length > 0
            ) {
              url = this.column.entityUrl
              this.column.params.forEach(item => {
                url = url.replace(
                  new RegExp(
                    '\\$\\{([\\s]*?)(' + item.code + '{1})([\\s]*?)([^}])*\\}'
                  ),
                  data[item.column]
                )
              })
            }
          }
          const object = {
            title: data[this.column['title']],
            params: params,
            setting: this.temp,
            entityTemp: this.column.entityTemplateId,
            temp: this.column.entityTemp,
            openType: this.column.entityOpenType,
            url: url
          }
          this.$emit('fetch-entity', object)
        }
      }
    }
  }
}

/**
 * 移动端辅助工具
 * @type {{}}
 */
export const tempDivider = {
  props: {
    temp: {
      type: Object,
      default() {
        return {}
      }
    },
    showHeader: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      setting: {}, // 设置信息
      cid: '', // 栏目编号
      image: '', // 图片地址
      type: null, // 类型（图片，还是文字）
      title: '', // 文字内容
      size: 0, // 文字大小
      baseURL: process.env.VUE_APP_BASE_API.substring(
        0,
        process.env.VUE_APP_BASE_API.length - 1
      )
    }
  },
  computed: {
    // 块状区域样式
    borderStyle() {
      // 是否全屏展示
      if (this.temp.sfdzqp === true) {
        return {
          position: 'absolute',
          left: '0px',
          right: '0px',
          top: '0px',
          bottom: '0px',
          paddingTop: this.temp.mtop + 'px',
          paddingLeft: this.temp.mleft + 'px',
          paddingRight: this.temp.mright + 'px',
          paddingBottom: this.temp.mbotton + 'px'
        }
      }
      return {
        minHeight: this.temp.defaultHeight,
        paddingTop: this.temp.mtop + 'px',
        paddingLeft: this.temp.mleft + 'px',
        paddingRight: this.temp.mright + 'px',
        paddingBottom: this.temp.mbotton + 'px'
      }
    },
    // 内容区域样式
    bodyStyle() {
      let boxShadow = '' // 是否显示边框
      const borderRadius = this.temp.topLeft + 'px ' +
        this.temp.topRight + 'px ' + this.temp.bottomRight + 'px ' + this.temp.bottomLeft + 'px' // 圆角大小
      if (this.temp.sfxsbk) { // 如果显示边框
        boxShadow = '0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)'
      }
      let backgroundColor = '' // 背景颜色
      if (this.temp.sfxsbjs) {
        backgroundColor = this.temp.backgroundColor
      }
      return {
        boxShadow: boxShadow,
        borderRadius: borderRadius,
        backgroundColor: backgroundColor,
        color: this.temp.fontColor,
        minHeight: this.temp.defaultHeight
      }
    }
  },
  watch: {
    temp: {
      handler(newData) {
        if (this.showHeader) {
          this.setting = JSON.parse(newData.data.pzx)
          this.cid = newData.data.id
        } else {
          this.setting = JSON.parse(newData.pzx)
          this.cid = newData.id
        }
        this.type = this.setting.type
        this.image = this.setting.content
        this.title = this.setting.content
        this.size = (this.setting.fontSize === null || this.setting.fontSize === undefined) ? 0 : this.setting.fontSize
      },
      immediate: true, // 父组件第一次传值时，执行handler，false则第一次不执行
      deep: false // formType为对象时，设置为true，此属性监听对象发生变化
    }
  }
}
